package com.paiai.lslease.action.apphouse;

import com.paiai.lslease.auto.model.AppFurniture;
import com.paiai.lslease.auto.model.AppHouse;
import com.paiai.lslease.auto.model.AppLock;
import com.paiai.lslease.auto.model.AppSysUser;
import com.paiai.lslease.base.BaseAction;
import com.paiai.lslease.model.AppHouseInfo;
import com.paiai.lslease.model.AppHouseInfoLandlordQuery;
import com.paiai.lslease.model.AppHouseInfoTenantQuery;
import com.paiai.lslease.model.LockExternal;
import com.paiai.lslease.service.apphouse.AppHouseService;
import com.paiai.lslease.service.landlordauth.AppLandlordAuthService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.util.*;

public class AppHouseAction extends BaseAction {

    private static final Logger logger = LoggerFactory.getLogger(AppHouseAction.class);

    private AppHouseService appHouseService;
    @Autowired
    private AppLandlordAuthService appLandlordAuthService;

    /**
     * 房源属性
     */
    private String houseId;
    private String houseName;
    private String houseAddress;

    /**
     * 用户属性
     */
    private String userId;//属性用户ID
    private String operateUserId;//操作者用户ID

    /**
     * 房源家具属性
     */
    private String washingMachineFlag;
    private String microWaveOvenFlag;
    private String refrigeratorFlag;
    private String rangeHoodFlag;
    private String sofaFlag;
    private String bedFlag;
    private String deskFlag;
    private String calorifierFlag;

    /**
     * 房源图片属性
     */
    private File housePic;
    private String housePicFileName;
    private String housePicContentType;
    private String housePicIndex;

    @Override
    public String toString() {
        return "AppHouseAction{" +
                "appHouseService=" + appHouseService +
                ", houseId='" + houseId + '\'' +
                ", houseName='" + houseName + '\'' +
                ", houseAddress='" + houseAddress + '\'' +
                ", userId='" + userId + '\'' +
                ", operateUserId='" + operateUserId + '\'' +
                ", washingMachineFlag='" + washingMachineFlag + '\'' +
                ", microWaveOvenFlag='" + microWaveOvenFlag + '\'' +
                ", refrigeratorFlag='" + refrigeratorFlag + '\'' +
                ", rangeHoodFlag='" + rangeHoodFlag + '\'' +
                ", sofaFlag='" + sofaFlag + '\'' +
                ", bedFlag='" + bedFlag + '\'' +
                ", deskFlag='" + deskFlag + '\'' +
                ", calorifierFlag='" + calorifierFlag + '\'' +
                ", housePic=" + housePic +
                ", housePicFileName='" + housePicFileName + '\'' +
                ", housePicContentType='" + housePicContentType + '\'' +
                ", housePicIndex='" + housePicIndex + '\'' +
                '}';
    }

    /**
     * 添加房源
     */
    public void insertAppHouseInfo() {
        try {
            logger.info("添加房源=================" + this.toString());
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作者ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作者ID格式错误");
                return;
            }
            //检查用户是否已注册
            if (!appSysUserService.checkUserRegisterState(Integer.parseInt(operateUserId))) {
                sendFailureMsg("操作者未注册，不能添加房源");
                return;
            }
            if (StringUtils.isEmpty(houseName)) {
                sendFailureMsg("房源名称不能为空");
                return;
            }
            if (StringUtils.isEmpty(houseAddress)) {
                sendFailureMsg("房源地址不能为空");
                return;
            }
            AppHouseInfo appHouseInfo;
            AppHouse appHouse = new AppHouse();
            appHouse.setHouseName(houseName);
            appHouse.setHouseAddress(houseAddress);
            appHouse.setLandlordId(Integer.valueOf(operateUserId));
            appHouseInfo = appHouseService.insertAppHouseInfo(appHouse);
            if (appHouseInfo == null) {
                sendFailureMsg("添加房源失败");
                return;
            }
            sendSuccesseMsg(appHouseInfo, "添加房源成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("添加房源失败");
        }
    }

    /**
     * 修改房源基本信息
     */
    public void modifyAppHouseBaseInfo() {
        try {
            logger.info("修改房源基本信息=================" + this.toString());
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作者ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作者ID格式错误");
                return;
            }
            //检查用户是否已注册
            if (!appSysUserService.checkUserRegisterState(Integer.parseInt(operateUserId))) {
                sendFailureMsg("操作者未注册，不能修改房源基本信息");
                return;
            }
            if (StringUtils.isEmpty(houseId)) {
                sendFailureMsg("房源ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(houseId)) {
                sendFailureMsg("房源ID格式错误");
                return;
            }
            if (StringUtils.isEmpty(houseName) && StringUtils.isEmpty(houseAddress)) {
                sendFailureMsg("房源名称与房源地址不能同时为空");
                return;
            }
            if (!appHouseService.checkHouseExist(Integer.parseInt(houseId))) {
                sendFailureMsg("房源不存在");
                return;
            }
            if (!appHouseService.houseBelongUser(Integer.parseInt(houseId), Integer.parseInt(operateUserId))) {
                sendFailureMsg("房源不属于该用户");
                return;
            }
            AppHouseInfo appHouseInfo;
            AppHouse appHouse = new AppHouse();
            appHouse.setHouseName(houseName);
            appHouse.setHouseAddress(houseAddress);
            appHouseInfo = appHouseService.modifyAppHouseBaseInfo(Integer.parseInt(houseId), appHouse);
            if (appHouseInfo == null) {
                sendFailureMsg("修改房源基本信息失败");
                return;
            }
            sendSuccesseMsg(appHouseInfo, "修改房源基本信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("修改房源基本信息失败");
        }
    }

    /**
     * 修改房源家具信息
     */
    public void modifyAppHouseFurnitureInfo() {
        try {
            logger.info("修改房源家具信息=================" + this.toString());
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作者ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作者ID格式错误");
                return;
            }
            //检查用户是否已注册
            if (!appSysUserService.checkUserRegisterState(Integer.parseInt(operateUserId))) {
                sendFailureMsg("操作者未注册，不能修改房源家具信息");
                return;
            }
            if (StringUtils.isEmpty(houseId)) {
                sendFailureMsg("房源ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(houseId)) {
                sendFailureMsg("房源ID格式错误");
                return;
            }
            if (!appHouseService.checkHouseExist(Integer.parseInt(houseId))) {
                sendFailureMsg("房源不存在");
                return;
            }
            if (!appHouseService.houseBelongUser(Integer.parseInt(houseId), Integer.parseInt(operateUserId))) {
                sendFailureMsg("房源不属于该用户");
                return;
            }
            AppHouseInfo appHouseInfo;
            AppFurniture appFurniture = new AppFurniture();
            appFurniture.setWashingMachineFlag(StringUtils.isEmpty(washingMachineFlag) || !StringUtils.isNumeric(washingMachineFlag) ? 2 : Integer.parseInt(washingMachineFlag) != 1 ? 2 : 1);
            appFurniture.setMicroWaveOvenFlag(StringUtils.isEmpty(microWaveOvenFlag) || !StringUtils.isNumeric(microWaveOvenFlag) ? 2 : Integer.parseInt(microWaveOvenFlag) != 1 ? 2 : 1);
            appFurniture.setRefrigeratorFlag(StringUtils.isEmpty(refrigeratorFlag) || !StringUtils.isNumeric(refrigeratorFlag) ? 2 : Integer.parseInt(refrigeratorFlag) != 1 ? 2 : 1);
            appFurniture.setRangeHoodFlag(StringUtils.isEmpty(rangeHoodFlag) || !StringUtils.isNumeric(rangeHoodFlag) ? 2 : Integer.parseInt(rangeHoodFlag) != 1 ? 2 : 1);
            appFurniture.setSofaFlag(StringUtils.isEmpty(sofaFlag) || !StringUtils.isNumeric(sofaFlag) ? 2 : Integer.parseInt(sofaFlag) != 1 ? 2 : 1);
            appFurniture.setBedFlag(StringUtils.isEmpty(bedFlag) || !StringUtils.isNumeric(bedFlag) ? 2 : Integer.parseInt(bedFlag) != 1 ? 2 : 1);
            appFurniture.setDeskFlag(StringUtils.isEmpty(deskFlag) || !StringUtils.isNumeric(deskFlag) ? 2 : Integer.parseInt(deskFlag) != 1 ? 2 : 1);
            appFurniture.setCalorifierFlag(StringUtils.isEmpty(calorifierFlag) || !StringUtils.isNumeric(calorifierFlag) ? 2 : Integer.parseInt(calorifierFlag) != 1 ? 2 : 1);
            appHouseInfo = appHouseService.modifyAppHouseFurnitureInfo(Integer.parseInt(houseId), appFurniture);
            if (appHouseInfo == null) {
                sendFailureMsg("修改房源家具信息失败");
                return;
            }
            sendSuccesseMsg(appHouseInfo, "修改房源家具信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("修改房源家具信息失败");
        }
    }

    /**
     * 修改房源图片信息
     */
    public void modifyAppHousePicInfo() {
        try {
            logger.info("修改房源图片信息=================" + this.toString());
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作者ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作者ID格式错误");
                return;
            }
            //检查用户是否已注册
            if (!appSysUserService.checkUserRegisterState(Integer.parseInt(operateUserId))) {
                sendFailureMsg("操作者未注册，不能修改房源家具信息");
                return;
            }
            if (StringUtils.isEmpty(houseId)) {
                sendFailureMsg("房源ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(houseId)) {
                sendFailureMsg("房源ID格式错误");
                return;
            }
            if (housePic == null) {
                sendFailureMsg("没有图片");
                return;
            }
            if (StringUtils.isEmpty(housePicIndex)) {
                sendFailureMsg("图片索引不能为空");
                return;
            }
            if (!StringUtils.isNumeric(housePicIndex)) {
                sendFailureMsg("图片索引格式异常");
                return;
            }
            if (Integer.parseInt(housePicIndex) < 0 || Integer.parseInt(housePicIndex) > 19) {
                sendFailureMsg("图片索引只能在0-19之间");
                return;
            }
            if (!appHouseService.checkHouseExist(Integer.parseInt(houseId))) {
                sendFailureMsg("房源不存在");
                return;
            }
            if (!appHouseService.houseBelongUser(Integer.parseInt(houseId), Integer.parseInt(operateUserId))) {
                sendFailureMsg("房源不属于该用户");
                return;
            }
            AppHouseInfo appHouseInfo = appHouseService.modifyAppHousePicInfo(Integer.parseInt(houseId), housePic, housePicFileName, housePicContentType, Integer.parseInt(housePicIndex));
            if (appHouseInfo == null) {
                sendFailureMsg("修改房源图片信息失败");
                return;
            }
            sendSuccesseMsg(appHouseInfo, "修改房源图片信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("修改房源图片信息失败");
        }
    }

    /**
     * 获取房源列表
     */
    public void getApphouseInfoList() {
        try {
            logger.info("获取房源列表=================" + this.toString());
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作者ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作者ID格式错误");
                return;
            }
            //检查用户是否已注册
            if (!appSysUserService.checkUserRegisterState(Integer.parseInt(operateUserId))) {
                sendFailureMsg("操作者未注册，不能获取指定用户的房源列表");
                return;
            }
            if (StringUtils.isEmpty(userId)) {
                sendFailureMsg("指定的用户ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(userId)) {
                sendFailureMsg("指定的用户ID格式错误");
                return;
            }
            //检查用户是否已注册
            if (!appSysUserService.checkUserRegisterState(Integer.parseInt(userId))) {
                sendFailureMsg("指定的用户未注册，不能获取房源列表");
                return;
            }
            List appHouseInfoList = appHouseService.getApphouseInfoList(Integer.parseInt(userId));
            Collections.sort(appHouseInfoList, new Comparator<Object>() {
                @Override
                public int compare(Object o1, Object o2) {
                    Date time1 = null;
                    if (o1 instanceof AppHouseInfoLandlordQuery) {
                        AppHouseInfoLandlordQuery appHouseInfoLandlordQuery = (AppHouseInfoLandlordQuery) o1;
                        time1 = appHouseInfoLandlordQuery.getUpdateTime();
                        List<AppLock> appLockList1 = appHouseInfoLandlordQuery.getAppLockList();
                        if (appLockList1 != null && appLockList1.size() > 0) {
                            for (AppLock appLock : appLockList1) {
                                if (time1 == null || time1.getTime() < appLock.getUpdateTime().getTime()) {
                                    time1 = appLock.getUpdateTime();
                                }
                            }
                        }
                    } else if (o1 instanceof AppHouseInfoTenantQuery) {
                        AppHouseInfoTenantQuery appHouseInfoTenantQuery = (AppHouseInfoTenantQuery) o1;
                        time1 = appHouseInfoTenantQuery.getUpdateTime();
                        List<LockExternal> lockExternalList = appHouseInfoTenantQuery.getLockExternalList();
                        if (lockExternalList != null && lockExternalList.size() > 0) {
                            for (LockExternal lockExternal : lockExternalList) {
                                if (time1 == null || time1.getTime() < lockExternal.getRentingTime().getTime()) {
                                    time1 = lockExternal.getUpdateTime();
                                }
                            }
                        }
                    }
                    Date time2 = null;
                    if (o2 instanceof AppHouseInfoLandlordQuery) {
                        AppHouseInfoLandlordQuery appHouseInfoLandlordQuery = (AppHouseInfoLandlordQuery) o2;
                        time2 = appHouseInfoLandlordQuery.getUpdateTime();
                        List<AppLock> appLockList2 = appHouseInfoLandlordQuery.getAppLockList();
                        if (appLockList2 != null && appLockList2.size() > 0) {
                            for (AppLock appLock : appLockList2) {
                                if (time2 == null || time2.getTime() < appLock.getUpdateTime().getTime()) {
                                    time2 = appLock.getUpdateTime();
                                }
                            }
                        }
                    } else if (o2 instanceof AppHouseInfoTenantQuery) {
                        AppHouseInfoTenantQuery appHouseInfoTenantQuery = (AppHouseInfoTenantQuery) o2;
                        time2 = appHouseInfoTenantQuery.getUpdateTime();
                        List<LockExternal> lockExternalList2 = appHouseInfoTenantQuery.getLockExternalList();
                        if (lockExternalList2 != null && lockExternalList2.size() > 0) {
                            for (LockExternal lockExternal : lockExternalList2) {
                                if (time2 == null || time2.getTime() < lockExternal.getRentingTime().getTime()) {
                                    time2 = lockExternal.getUpdateTime();
                                }
                            }
                        }
                    }
                    if (time1 == null || time2 == null) {
                        return 0;
                    }
                    return (int) (time2.getTime()/1000 - time1.getTime()/1000);
                }
            });
            sendSuccesseMsg(appHouseInfoList, "获取房源列表成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("获取房源列表失败");
        }
    }

    /**
     * 根据房源ID获取单个房源信息
     */
    public void getSingleApphouseInfoById() {
        try {
            logger.info("根据房源ID获取单个房源信息=================" + this.toString());
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作者ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作者ID格式错误");
                return;
            }
            //检查用户是否已注册
            if (!appSysUserService.checkUserRegisterState(Integer.parseInt(operateUserId))) {
                sendFailureMsg("操作者未注册，不能获取指定用户的房源列表");
                return;
            }
            if (StringUtils.isEmpty(houseId)) {
                sendFailureMsg("房源ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(houseId)) {
                sendFailureMsg("房源ID格式错误");
                return;
            }
            if (!appHouseService.checkHouseExist(Integer.parseInt(houseId))) {
                sendFailureMsg("房源不存在");
                return;
            }
            AppHouse appHouse = appHouseService.getAppHouseInfo(Integer.parseInt(houseId));
            if (appHouse == null) {
                sendSuccesseMsg("根据房源ID获取单个房源信息失败");
                return;
            }
            sendSuccesseMsg(appHouse, "根据房源ID获取单个房源信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("根据房源ID获取单个房源信息失败");
        }
    }

    /**
     * 删除房源
     */
    public void deleteAppHouseById() {
        logger.info("删除房源=================" + this.toString());
        try {
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作者ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作者ID格式错误");
                return;
            }
            //检查用户是否已注册
            AppSysUser appSysUser = appSysUserService.getAppSysUserInfoById(Integer.parseInt(operateUserId));
            if (appSysUser == null) {
                sendFailureMsg("操作者未注册，不能删除房源");
                return;
            }
            if (StringUtils.isEmpty(houseId)) {
                sendFailureMsg("房源ID不能为空");
                return;
            }
            if (!appHouseService.checkHouseExist(Integer.parseInt(houseId))) {
                sendFailureMsg("房源不存在");
                return;
            }
            if (!appHouseService.houseBelongUser(Integer.parseInt(houseId), Integer.parseInt(operateUserId))) {
                sendFailureMsg("房源不属于该用户");
                return;
            }
            if (appSysUserService.userBelongLandlord(Integer.parseInt(operateUserId))) {//房东删除房源
                if (!appHouseService.deleteAppHouseById(Integer.parseInt(houseId))) {
                    sendFailureMsg("删除房源失败");
                    return;
                }
            } else if (appSysUserService.userBelongLandlordAuthManagerById(Integer.parseInt(operateUserId))) {//授权管理员删除房源
                if (!appLandlordAuthService.deleteAuthedHouse(appSysUser.getMobile(), Integer.parseInt(houseId))) {
                    sendFailureMsg("删除房源失败");
                    return;
                }
            }
            sendSuccesseMsg("删除房源成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("删除房源失败");
        }
    }

    /**
     * 查询简单的房源列表信息
     */
    public void selectSimpleHouseList() {
        logger.info("查询简单的房源列表信息=================" + this.toString());
        try {
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作者ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作者ID格式错误");
                return;
            }
            //检查用户是否已注册
            if (!appSysUserService.checkUserRegisterState(Integer.parseInt(operateUserId))) {
                sendFailureMsg("操作者未注册，不能获取指定用户的房源列表");
                return;
            }
            if (StringUtils.isEmpty(userId)) {
                sendFailureMsg("指定的用户ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(userId)) {
                sendFailureMsg("指定的用户ID格式错误");
                return;
            }
            //检查用户是否已注册
            if (!appSysUserService.checkUserRegisterState(Integer.parseInt(userId))) {
                sendFailureMsg("指定的用户未注册，不能获取房源列表");
                return;
            }
            List<AppHouse> appHouseList = appHouseService.selectSimpleHouseList(Integer.parseInt(userId));
            Collections.sort(appHouseList, new Comparator<AppHouse>() {
                @Override
                public int compare(AppHouse o1, AppHouse o2) {
                    if (o1 == null || o2 == null) {
                        return 0;
                    }
                    return (int) (o2.getUpdateTime().getTime()/1000 - o1.getUpdateTime().getTime()/1000);
                }
            });
            sendSuccesseMsg(appHouseList, "获取房源列表成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("获取房源列表失败");
        }
    }

    public void setHousePic(File housePic) {
        this.housePic = housePic;
    }

    public void setHousePicFileName(String housePicFileName) {
        this.housePicFileName = housePicFileName;
    }

    public void setHousePicContentType(String housePicContentType) {
        this.housePicContentType = housePicContentType;
    }

    public void setHousePicIndex(String housePicIndex) {
        this.housePicIndex = housePicIndex;
    }

    public void setAppHouseService(AppHouseService appHouseService) {
        this.appHouseService = appHouseService;
    }

    public void setHouseName(String houseName) {
        this.houseName = houseName;
    }

    public void setHouseAddress(String houseAddress) {
        this.houseAddress = houseAddress;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public void setOperateUserId(String operateUserId) {
        this.operateUserId = operateUserId;
    }

    public void setHouseId(String houseId) {
        this.houseId = houseId;
    }

    public void setWashingMachineFlag(String washingMachineFlag) {
        this.washingMachineFlag = washingMachineFlag;
    }

    public void setMicroWaveOvenFlag(String microWaveOvenFlag) {
        this.microWaveOvenFlag = microWaveOvenFlag;
    }

    public void setRefrigeratorFlag(String refrigeratorFlag) {
        this.refrigeratorFlag = refrigeratorFlag;
    }

    public void setRangeHoodFlag(String rangeHoodFlag) {
        this.rangeHoodFlag = rangeHoodFlag;
    }

    public void setSofaFlag(String sofaFlag) {
        this.sofaFlag = sofaFlag;
    }

    public void setBedFlag(String bedFlag) {
        this.bedFlag = bedFlag;
    }

    public void setDeskFlag(String deskFlag) {
        this.deskFlag = deskFlag;
    }

    public void setCalorifierFlag(String calorifierFlag) {
        this.calorifierFlag = calorifierFlag;
    }
}
